package com.qqt.csr.common.utils;

import cn.hutool.core.util.StrUtil;
import com.google.common.base.Stopwatch;
import com.qqt.csr.common.exception.BaseException;
import com.qqt.csr.common.exception.BizException;
import com.qqt.csr.common.exception.StatusCode;
import org.apache.commons.collections.MapUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHeaders;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.HttpClientUtils;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.apache.poi.ss.formula.functions.T;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;
import java.util.function.Supplier;

public class HttpClientUtil {

    private final static Logger logger = LoggerFactory.getLogger(HttpClientUtil.class);

    public final static String CHARSET = "UTF-8";
    /**
     * 默认HttpClient
     */
    private static volatile CloseableHttpClient defaultClient;

    public static class HttpConfig {

        /**
         * 连接池最大连接数（所有路由最大连接数相加不能超过）
         */
        private int maxTotal;
        /**
         * 每个路由最大连接数
         */
        private int maxPerRoute;
        /**
         * socket超时时间，单位毫秒
         */
        private int socketTimeout;
        /**
         * 连接超时时间，单位毫秒
         */
        private int connectTimeout;
        /**
         * 连接请求超时时间，单位毫秒
         */
        private int connectionRequestTimeout;
        /**
         * 证书文件路径
         */
        private String certFilePath;
        /**
         * 证书密码
         */
        private String certPassword;
        /**
         * 证书格式 X509、PKCS12、JKS
         */
        private String certType;

        /**
         * 最大连接数
         */
        public final static int MAXTOTAL = 5000;
        /**
         * 每个链路最大连接数
         */
        public final static int MAXPERROUTE = 5000;
        /**
         * Socket超时时间
         */
        public final static int SOCKETTIMEOUT = 10000;
        /**
         * 连接超时时间
         */
        public final static int CONNECTTIMEOUT = 1000;
        /**
         * 连接请求超时时间
         */
        public final static int CONNECTIONREQUESTTIMEOUT = 3000;

        /**
         * 最大连接数属性
         */
        public final static String PROP_MAXTOTAL = "http.maxTotal";
        /**
         * 每个链路最大连接数属性
         */
        public final static String PROP_MAXPERROUTE = "http.maxPerRoute";
        /**
         * Socket超时时间属性
         */
        public final static String PROP_SOCKETTIMEOUT = "http.socketTimeout";
        /**
         * 连接超时时间属性
         */
        public final static String PROP_CONNECTTIMEOUT = "http.connectTimeout";
        /**
         * 连接请求超时时间属性
         */
        public final static String PROP_CONNECTIONREQUESTTIMEOUT = "http.connectionRequestTimeout";

        public int getMaxTotal() {
            return maxTotal;
        }

        public void setMaxTotal(int maxTotal) {
            this.maxTotal = maxTotal;
        }

        public int getMaxPerRoute() {
            return maxPerRoute;
        }

        public void setMaxPerRoute(int maxPerRoute) {
            this.maxPerRoute = maxPerRoute;
        }

        public int getSocketTimeout() {
            return socketTimeout;
        }

        public void setSocketTimeout(int socketTimeout) {
            this.socketTimeout = socketTimeout;
        }

        public int getConnectTimeout() {
            return connectTimeout;
        }

        public void setConnectTimeout(int connectTimeout) {
            this.connectTimeout = connectTimeout;
        }

        public int getConnectionRequestTimeout() {
            return connectionRequestTimeout;
        }

        public void setConnectionRequestTimeout(int connectionRequestTimeout) {
            this.connectionRequestTimeout = connectionRequestTimeout;
        }

        public String getCertFilePath() {
            return certFilePath;
        }

        public void setCertFilePath(String certFilePath) {
            this.certFilePath = certFilePath;
        }

        public String getCertPassword() {
            return certPassword;
        }

        public void setCertPassword(String certPassword) {
            this.certPassword = certPassword;
        }

        public String getCertType() {
            return certType;
        }

        public void setCertType(String certType) {
            this.certType = certType;
        }

    }

    /**
     * 获取默认配置
     *
     * @return
     */
    public static HttpConfig getDefaultConfig() {
        HttpConfig config = new HttpConfig();
        config.setMaxTotal(Integer.parseInt(System.getProperty(HttpConfig.PROP_MAXTOTAL, HttpConfig.MAXTOTAL + "")));
        config.setMaxPerRoute(
                Integer.parseInt(System.getProperty(HttpConfig.PROP_MAXPERROUTE, HttpConfig.MAXPERROUTE + "")));
        config.setSocketTimeout(
                Integer.parseInt(System.getProperty(HttpConfig.PROP_SOCKETTIMEOUT, HttpConfig.SOCKETTIMEOUT + "")));
        config.setConnectTimeout(
                Integer.parseInt(System.getProperty(HttpConfig.PROP_CONNECTTIMEOUT, HttpConfig.CONNECTTIMEOUT + "")));
        config.setConnectionRequestTimeout(Integer.parseInt(System.getProperty(HttpConfig.PROP_CONNECTIONREQUESTTIMEOUT,
                HttpConfig.CONNECTIONREQUESTTIMEOUT + "")));
        return config;
    }

    /**
     * 创建HttpClient
     * <p>
     * 默认设置，如果系统变量配置了代理，则会走代理
     *
     * @return
     */
    public static CloseableHttpClient getDefaultHttpClient() {
        if (defaultClient == null) {
            synchronized (HttpClientUtil.class) {
                if (defaultClient == null) {
                    defaultClient = createHttpClient(getDefaultConfig());
                }
            }
        }
        return defaultClient;
    }

    /**
     * 创建HttpClient，根据配置参数HttpConfig，可设置http代理、HTTPS请求
     *
     * @param config
     * @return
     * @throws Exception
     */
    public static CloseableHttpClient createHttpClient(HttpConfig config) {
        RequestConfig.Builder builder = RequestConfig.custom();
        // socket超时，单位毫秒
        if (config.getSocketTimeout() > 0) {
            builder.setSocketTimeout(config.getSocketTimeout());
        }
        // 连接超时时间，单位毫秒
        if (config.getConnectTimeout() > 0) {
            builder.setConnectTimeout(config.getConnectTimeout());
        }
        // 连接请求超时时间，单位毫秒
        if (config.getConnectionRequestTimeout() > 0) {
            builder.setSocketTimeout(config.getConnectionRequestTimeout());
        }
        PoolingHttpClientConnectionManager connManager = null;
        connManager = new PoolingHttpClientConnectionManager();

        // 连接池最大连接数（所有路由最大连接数相加不能超过）
        if (config.getMaxTotal() > 0) {
            connManager.setMaxTotal(config.getMaxTotal());
        }
        // 连接池每个路由最大连接数
        if (config.getMaxPerRoute() > 0) {
            connManager.setDefaultMaxPerRoute(config.getMaxPerRoute());
        }
        RequestConfig requestConfig = builder.build();
        CloseableHttpClient client = HttpClients.custom()//
                .setConnectionManager(connManager)//
                .setDefaultRequestConfig(requestConfig)//
                .build();
        return client;

    }

    /**
     * 关闭httpClient连接
     *
     * @param httpClient
     */
    public static void closeHttpClient(CloseableHttpClient httpClient) {
        HttpClientUtils.closeQuietly(httpClient);
        httpClient = null;
    }

    /**
     * 使用默认HttpClient发送GET请求
     *
     * @param url
     * @return
     * @throws Exception
     */
    public static String get(String url) throws Exception {
        return get(getDefaultHttpClient(), url, null, null);
    }

    public static void downLoadFile(String url, Consumer<InputStream> consumer) throws Exception {
        downLoadFile(getDefaultHttpClient(), url, null, null,  consumer);
    }

    /**
     * 发送GET请求
     *
     * @param client
     * @param url
     * @return
     * @throws Exception
     */
    public static String get(CloseableHttpClient client, String url) throws Exception {
        return get(client, url, null, null);
    }

    /**
     * 使用默认HttpClient发送GET请求
     *
     * @param url
     * @param params
     * @return
     * @throws Exception
     */
    public static String get(String url, Map<String, String> params) throws Exception {
        return get(getDefaultHttpClient(), url, params, null);
    }

    /**
     * 使用默认HttpClient发送GET请求
     *
     * @param url
     * @param params
     * @param headers
     * @return
     * @throws Exception
     */
    public static String get(String url, Map<String, String> params, Map<String, String> headers) throws Exception {
        return get(getDefaultHttpClient(), url, params, headers);
    }

    /**
     * 发送GET请求
     *
     * @param client
     * @param url
     * @param params
     * @param headers
     * @return
     * @throws Exception
     */
    public static String get(CloseableHttpClient client, String url, Map<String, String> params,
                             Map<String, String> headers) throws Exception {
        CloseableHttpResponse response = null;
        try {
            if (params != null && params.size() > 0) {
                if (!url.contains("?")) {
                    url += "?1=1";
                }
                for (Map.Entry<String, String> entry : params.entrySet()) {
                    url += "&" + entry.getKey() + "=" + entry.getValue();
                    // url += "&" + entry.getKey() + "=" +
                    // URLEncoder.encode(entry.getValue(),CHARSET);
                }
            }
            HttpGet request = new HttpGet(url);
            request.addHeader(HttpHeaders.CONTENT_ENCODING, CHARSET);

            if (headers != null && headers.size() > 0) {
                for (Map.Entry<String, String> entry : headers.entrySet()) {
                    request.addHeader(entry.getKey(), entry.getValue());
                }
            }
            Stopwatch stopwatch = Stopwatch.createStarted();
            response = client.execute(request);
            stopwatch.stop();
            logger.info("get url:{}，耗时：{}ms", url, stopwatch.elapsed(TimeUnit.MILLISECONDS));
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode != 200) {
                request.abort();
                logger.error("Http request response error || rsp={}",
                        EntityUtils.toString(response.getEntity(), CHARSET));
                throw new IOException("Http request response error:" + response.getStatusLine());
            }
            HttpEntity entity = response.getEntity();
            String result = null;
            if (entity != null) {
                result = EntityUtils.toString(entity, CHARSET);
            }
            return result;
        } finally {
            // 包含 EntityUtils.consume(entity);
            HttpClientUtils.closeQuietly(response);
        }
    }

    public static void downLoadFile(CloseableHttpClient client, String url, Map<String, String> params,
                                        Map<String, String> headers, Consumer<InputStream> consumer) throws Exception {
        if (MapUtils.isNotEmpty(params)) {
            if (!url.contains("?")) {
                url += "?1=1";
            }
            for (Map.Entry<String, String> entry : params.entrySet()) {
                url += "&" + entry.getKey() + "=" + entry.getValue();
                // url += "&" + entry.getKey() + "=" +
                // URLEncoder.encode(entry.getValue(),CHARSET);
            }
        }
        HttpGet request = new HttpGet(url);
        request.addHeader(HttpHeaders.CONTENT_ENCODING, CHARSET);

        if (MapUtils.isNotEmpty(headers)) {
            for (Map.Entry<String, String> entry : headers.entrySet()) {
                request.addHeader(entry.getKey(), entry.getValue());
            }
        }

        try  (CloseableHttpResponse response = client.execute(request);
              InputStream is = response.getEntity().getContent()){
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode != 200) {
                request.abort();
                logger.warn("Http request response error || rsp={}", EntityUtils.toString(response.getEntity()));
                throw new IOException("Http request response error:" + response.getStatusLine());
            }
            consumer.accept(is);
        }
    }

    /**
     * 使用默认HttpClient发送POST请求
     *
     * @param url
     * @param params
     * @return
     * @throws Exception
     */
    public static String post(String url, Map<String, String> params) throws Exception {
        return post(getDefaultHttpClient(), url, params, null);
    }

    /**
     * 使用默认HttpClient发送POST请求
     *
     * @param url
     * @param params
     * @param headers
     * @return
     * @throws Exception
     */
    public static String post(String url, Map<String, String> params, Map<String, String> headers) throws Exception {
        return post(getDefaultHttpClient(), url, params, headers);
    }

    /**
     * 发送POST请求
     *
     * @param client
     * @param url
     * @param params
     * @return
     * @throws Exception
     */
    public static String post(CloseableHttpClient client, String url, Map<String, String> params,
                              Map<String, String> headers) throws Exception {
        CloseableHttpResponse response = null;
        try {
            HttpPost request = new HttpPost(url);
            request.addHeader(HttpHeaders.CONTENT_ENCODING, CHARSET);
            if (headers != null && headers.size() > 0) {
                for (Map.Entry<String, String> entry : headers.entrySet()) {
                    request.addHeader(entry.getKey(), entry.getValue());
                }
            }

            if (params != null && params.size() > 0) {
                List<BasicNameValuePair> nvps = new ArrayList<BasicNameValuePair>();
                for (Map.Entry<String, String> entry : params.entrySet()) {
                    nvps.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
                }
                request.setEntity(new UrlEncodedFormEntity(nvps, CHARSET));
            }
            response = client.execute(request);
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode != 200) {
                request.abort();
                logger.error("Http request response error || rsp={}",
                        EntityUtils.toString(response.getEntity(), CHARSET));
                throw new IOException("Http request response error:" + response.getStatusLine());
            }
            HttpEntity entity = response.getEntity();
            String result = null;
            if (entity != null) {
                result = EntityUtils.toString(entity, CHARSET);
            }
            return result;
        } finally {
            // 包含 EntityUtils.consume(entity);
            HttpClientUtils.closeQuietly(response);
        }
    }

    /**
     * 使用默认HttpClient执行一个HTTP POST JSON请求
     *
     * @param url
     * @param requestObject
     * @param responseClazz
     * @return
     * @throws Exception
     */
    public static <T> T postJson(String url, Object requestObject, Class<T> responseClazz) throws Exception {
        return postJson(getDefaultHttpClient(), url, requestObject, null, responseClazz);
    }

    /**
     * 使用默认HttpClient执行一个HTTP POST JSON请求
     *
     * @param url
     * @param requestObject
     * @param headers
     * @param responseClazz
     * @return
     * @throws Exception
     */
    public static <T> T postJson(String url, Object requestObject, Map<String, String> headers, Class<T> responseClazz) throws Exception {
        return postJson(getDefaultHttpClient(), url, requestObject, headers, responseClazz);
    }

    /**
     * 执行一个HTTP POST JSON请求
     *
     * @param client
     * @param url
     * @param requestObject
     * @param responseClazz
     * @return
     * @throws Exception
     */
    public static <T> T postJson(CloseableHttpClient client, String url, Object requestObject, Class<T> responseClazz)
            throws Exception {
        return postJson(client, url, requestObject, null, responseClazz);
    }

    /**
     * 执行一个HTTP POST JSON请求
     *
     * @param client
     * @param url
     * @param requestObject
     * @param headers
     * @param responseClazz
     * @return
     * @throws Exception
     */
    public static <T> T postJson(CloseableHttpClient client, String url, Object requestObject,
                                 Map<String, String> headers, Class<T> responseClazz) throws Exception {
        String reqJson = null;
        if (requestObject != null) {
            if (requestObject instanceof String) {
                reqJson = (String) requestObject;
            } else {
                reqJson = JsonUtil.toJson(requestObject);
            }
        }
        String ret = postJson(client, url, reqJson, headers);
        if (ret == null) {
            return null;
        }
        if (String.class.isAssignableFrom(responseClazz)) {
            return (T) ret;
        }
        return JsonUtil.toObject(ret, responseClazz);
    }

    /**
     * 执行一个HTTP POST JSON请求
     *
     * @param client
     * @param url
     * @param json
     * @return
     * @throws Exception
     */
    public static String postJson(CloseableHttpClient client, String url, String json) throws Exception {
        return post(client, url, json, "application/json", null);
    }

    /**
     * 执行一个HTTP POST JSON请求
     *
     * @param client
     * @param url
     * @param json
     * @param headers
     * @return
     * @throws Exception
     */
    public static String postJson(CloseableHttpClient client, String url, String json, Map<String, String> headers)
            throws Exception {
        return post(client, url, json, "application/json", headers);
    }

    /**
     * 执行一个HTTP POST XML请求
     *
     * @param client
     * @param url
     * @param xml
     * @return
     * @throws Exception
     */
    public static String postXml(CloseableHttpClient client, String url, String xml) throws Exception {
        return post(client, url, xml, "text/xml", null);
    }

    /**
     * 执行一个HTTP POST XML请求
     *
     * @param client
     * @param url
     * @param xml
     * @param headers
     * @return
     * @throws Exception
     */
    public static String postXml(CloseableHttpClient client, String url, String xml, Map<String, String> headers)
            throws Exception {
        return post(client, url, xml, "text/xml", headers);
    }

    /**
     * 执行一个HTTP POST JSON请求
     *
     * @param client
     * @param url
     * @return
     * @throws Exception
     */
    public static String post(CloseableHttpClient client, String url, String data, String contentType,
                              Map<String, String> headers) throws Exception {
        CloseableHttpResponse response = null;
        HttpPost request = null;
        try {
            request = new HttpPost(url);
            if (StrUtil.isNotEmpty(contentType)) {
                request.addHeader(HttpHeaders.CONTENT_TYPE, contentType);
            }

            if (headers != null && headers.size() > 0) {
                for (Map.Entry<String, String> entry : headers.entrySet()) {
                    request.addHeader(entry.getKey(), entry.getValue());
                }
            }

            request.addHeader(HttpHeaders.CONTENT_ENCODING, CHARSET);
            if (StrUtil.isNotEmpty(data)) {
                request.setEntity(new StringEntity(data, CHARSET));
            }
            Stopwatch stopwatch = Stopwatch.createStarted();
            response = client.execute(request);
            stopwatch.stop();
            logger.info("post url:{}，耗时：{}ms", url, stopwatch.elapsed(TimeUnit.MILLISECONDS));
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode != 200) {
                request.abort();
                logger.error("Http request response error || rsp={}",
                        EntityUtils.toString(response.getEntity(), CHARSET));
                throw new IOException("Http request response error:" + response.getStatusLine());
            }
            HttpEntity entity = response.getEntity();
            String result = null;
            if (entity != null) {
                result = EntityUtils.toString(entity, CHARSET);
            }
            return result;
        } finally {
            // 包含 EntityUtils.consume(entity);
            HttpClientUtils.closeQuietly(response);
        }
    }

    /**
     * http post 请求
     *
     * @param client
     * @param url
     * @param params
     * @param data
     * @param contentType
     * @param headers
     * @return
     * @throws IOException
     */
    public static String post(CloseableHttpClient client, String url, Map<String, String> params, String data,
                              String contentType, Map<String, String> headers) throws IOException {
        CloseableHttpResponse response = null;
        HttpPost request = null;
        try {
            if (params != null && params.size() > 0) {
                if (!url.contains("?")) {
                    url += "?";
                }
                for (Map.Entry<String, String> entry : params.entrySet()) {
                    String param = entry.getKey() + "=" + entry.getValue() + "&";
                    url = String.join("&", url, param);
                }
            }
            request = new HttpPost(url);
            if (StrUtil.isNotEmpty(contentType)) {
                request.addHeader(HttpHeaders.CONTENT_TYPE, contentType);
            }

            if (headers != null && headers.size() > 0) {
                for (Map.Entry<String, String> entry : headers.entrySet()) {
                    request.addHeader(entry.getKey(), entry.getValue());
                }
            }

            request.addHeader(HttpHeaders.CONTENT_ENCODING, CHARSET);
            if (StrUtil.isNotEmpty(data)) {
                request.setEntity(new StringEntity(data, CHARSET));
            }
            response = client.execute(request);
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode != 200) {
                request.abort();
                logger.error("Http request response error || rsp={}",
                        EntityUtils.toString(response.getEntity(), CHARSET));
                throw new IOException("Http request response error:" + response.getStatusLine());
            }
            HttpEntity entity = response.getEntity();
            String result = null;
            if (entity != null) {
                result = EntityUtils.toString(entity, CHARSET);
            }
            return result;
        } finally {
            // 包含 EntityUtils.consume(entity);
            HttpClientUtils.closeQuietly(response);
        }
    }


}
